package com.shou.controller.admin;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.shou.controller.MyController;
import com.shou.entity.Activity;
import com.shou.service.impl.ActivityService;

@Controller
@RequestMapping("/admin/activity")
public class ActivityController extends MyController{

	@Autowired
	ActivityService activityService;
	
	@RequestMapping("/list")
	public String list(Model model,HttpServletRequest request) {
		model.addAttribute("list", activityService.activityList());
		return "/admin/activity/list";
	}
	
	@RequestMapping("/edit")
	public String edit(Integer activityId,Model model) {
		
		model.addAttribute("info",activityService.getActivity(activityId));
		return "/admin/activity/edit";
	}
	
	@RequestMapping("/save")
	public ResponseEntity<String> save(Activity activity) {
		
		String msg = "保存成功";
		boolean status = true;
		if(StringUtils.isBlank(activity.getActivityName())) {
			status = false;
			msg = "请输入活动名称";
		}
		else if(StringUtils.isBlank(activity.getDescription())) {
			status = false;
			msg = "请输入内容";
		}
		else if(StringUtils.isBlank(activity.getImageUrl())){
			status = false;
			msg = "请输入图片路径";
		}
		else if(StringUtils.isBlank(activity.getLinkUrl())){
			status = false;
			msg = "请输入链接地址";
		}
		else {
			try{
				activityService.saveActivity(activity);				
			}
			catch(Exception e){
				e.printStackTrace();
				status = false;
				msg = "保存失败";
			}
		}
		return renderMsg(status, msg);
	}
	
	@RequestMapping("/uploadActivity")
	public ResponseEntity<String> uploadActivity(@RequestParam("cmfile") CommonsMultipartFile cmfile, Integer fsize,HttpServletResponse response) {
		
		String msg = "上传成功";
		boolean status = true;
		Map<String,String> map = new HashMap<>();
		try{			
			String filePath = activityService.uploadActivityImage(cmfile, fsize);
			map.put("filePath", filePath);
		}
		catch(Exception e){
			e.printStackTrace();
			status = false;
			msg = "上传失败";
		}
		return renderData(status, msg,map);
	}
}
